#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 2005;
const int B = 13;
const int MOD = 998244353;

int p, m;
int head[N];
int ver[N * 40], W[N * 40], Next[N * 40], tot;
int mx = 0;
void add(int u, int v, int w) {
  ++tot;
  ver[tot] = v;
  W[tot] = w;
  Next[tot] = head[u];
  head[u] = tot;
}
int dis[N][N];
void dijkstra(int s, int dis[N]) {
  priority_queue<pii, vector<pii>, greater<pii>> pq;
  pq.push(pii(0, s));
  dis[s] = 0;
  while (pq.size()) {
    pii now = pq.top();
    pq.pop();
    int d = now.first, u = now.second;
    if (d > dis[u]) continue;
    for (int i = head[u]; i; i = Next[i]) {
      int v = ver[i];
      int w = W[i];
      if (dis[v] > d + w) {
        dis[v] = d + w;
        pq.push(pii(dis[v], v));
      }
    }
  }
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> p >> m;
  rep(i, 1, p - 1) rep(j, 1, p - 1) {
    if (abs(i - j) <= B) {
      add(i, i * j % p, abs(i - j));
    }
  }
  memset(dis, 0x3f, sizeof(dis));
  rep(i, 1, p - 1) dijkstra(i, dis[i]);
  ll f = 1, sum = 0;
  rep(i, 1, p - 1) rep(j, 1, p - 1) {
    sum += dis[i][j] * f % MOD;
    f = f * m % MOD;
  }
  cout << sum % MOD;
  return 0;
}